/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package history;

import avenue.Session;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.swing.JOptionPane;
import model.Payment;
import model.RolePermission;
import model.Station;
import model.Vehicle;

/**
 *
 * @author chrysa
 */
public class PayHistory extends javax.swing.JInternalFrame {

    /**
     * Creates new form HistoryPassForm
     */
    public PayHistory() {
        em = Session.emf.createEntityManager();
        em.getTransaction().begin();
        payments = new ArrayList<>(); 
        initComponents();
        stationComboBox.setSelectedItem(Session.getUser().getStationId());
        RolePermission rp = Session.GetPermission(Session.LOG_MODULE);
        stationComboBox.setEnabled(!rp.getStationLevelAccess());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        paymentList = org.jdesktop.observablecollections.ObservableCollections.observableList(payments);
        stationQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("SELECT s FROM Station s");
        stationList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : stationQuery.getResultList();
        jLabel1 = new javax.swing.JLabel();
        cardIdTF = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        regNumberTF = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        searchButton = new javax.swing.JButton();
        fromDateField = new com.toedter.calendar.JDateChooser();
        toDateField = new com.toedter.calendar.JDateChooser();
        cancelButton = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        stationComboBox = new javax.swing.JComboBox();

        setIconifiable(true);
        setMaximizable(true);
        setTitle("Ιστορικό Πληρωμών");

        jLabel1.setText("Αρ. Κάρτας:");

        jLabel2.setText("Αρ. Κυκλοφορίας:");

        jLabel3.setText("Από:");

        jLabel4.setText("Έως:");

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, paymentList, jTable1, "");
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${cardId}"));
        columnBinding.setColumnName("Κάρτα");
        columnBinding.setColumnClass(model.Card.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${paymentTimestamp}"));
        columnBinding.setColumnName("Ώρα");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${oldBalance}"));
        columnBinding.setColumnName("Πρ. Υπόλοιπο");
        columnBinding.setColumnClass(java.math.BigDecimal.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${payment}"));
        columnBinding.setColumnName("Πληρωμή");
        columnBinding.setColumnClass(java.math.BigDecimal.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane1.setViewportView(jTable1);

        searchButton.setText("Αναζήτηση");
        searchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchButtonActionPerformed(evt);
            }
        });

        cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.gif"))); // NOI18N
        cancelButton.setText("Άκυρο");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        jLabel5.setText("Σταθμός");

        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, stationList, stationComboBox);
        bindingGroup.addBinding(jComboBoxBinding);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(23, 23, 23)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(2, 2, 2)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(jLabel5)
                                            .addComponent(jLabel3))))
                                .addGap(29, 29, 29))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jLabel2)))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(stationComboBox, javax.swing.GroupLayout.Alignment.TRAILING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(cardIdTF)
                            .addComponent(regNumberTF)
                            .addComponent(fromDateField, javax.swing.GroupLayout.DEFAULT_SIZE, 150, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(searchButton))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(toDateField, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(0, 410, Short.MAX_VALUE)
                                .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jScrollPane1))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cardIdTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(searchButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(regNumberTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(fromDateField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4)))
                    .addComponent(toDateField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(stationComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(cancelButton)
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed
        
        paymentList.removeAll(payments);
        
        String sql = "select c from Payment c";        
        
        Station st = (Station) stationComboBox.getSelectedItem();
        sql += " where c.stationId = :st";
        
        Date apo = fromDateField.getDate();
        if (apo != null) {
            sql += " and c.paymentTimestamp >= :apo";
        }
        
        Date eos = toDateField.getDate();
        if (eos != null) {
            sql += " and c.paymentTimestamp <= :eos";
        }
        
        Integer cardId = 0;
        String card = cardIdTF.getText().trim();
        if (!card.equals("")) {
            try { 
                cardId = Integer.parseInt(card);
                sql += " and c.cardId.barcode = :cid";
            } catch(NumberFormatException ex) { 
                JOptionPane.showMessageDialog(this,"Μη έγκυρος αριθμός κάρτας.");
                return;
            }
        }
        
        String regNumber = regNumberTF.getText().trim();                
        if (!regNumber.equals("")) {
            Query vehicleQuery = em.createQuery("select v from Vehicle v where "
                    + "v.regNumber = :regnum");

            vehicleQuery.setParameter("regnum", regNumber);

            try { 
                // Εκτέλεση της επερώτησης
                Vehicle vehicle = (Vehicle) vehicleQuery.getSingleResult();
                if (cardId == 0) {
                    cardId = vehicle.getCardId().getBarcode();
                    sql += " and c.cardId.barcode = :cid";
                } else {
                    if (cardId != vehicle.getCardId().getBarcode()) {
                        JOptionPane.showMessageDialog(this,"Ο συνδυασμός οχήματος/κάρτας δεν βρέθηκε.");
                        return;
                    }
                }
            } catch(NoResultException ex) { 
                // Το όχημα δεν βρέθηκε
                JOptionPane.showMessageDialog(this,"Ο αρ. κυκλοφορίας δεν βρέθηκε.");
                return;
            } catch(Exception ex) { 
                JOptionPane.showMessageDialog(this,ex.getMessage());
                return;
            }
        }
        
        sql += " order by c.paymentTimestamp desc";  
        Query q = em.createQuery(sql);
        q.setParameter("st", st);
        if (apo != null) {
            q.setParameter("apo", apo);
        }
        if (eos != null) {
            q.setParameter("eos", eos);
        }
        if (cardId != 0) {
            q.setParameter("cid", cardId);
        }
        try {
            paymentList.addAll(q.getResultList());
        } catch(Exception ex) { 
            JOptionPane.showMessageDialog(this,ex.getMessage());
        }
    }//GEN-LAST:event_searchButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        try {
            em.getTransaction().rollback();
            this.dispose();
        }
        catch (Exception ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }//GEN-LAST:event_cancelButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JTextField cardIdTF;
    private com.toedter.calendar.JDateChooser fromDateField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private java.util.List<Payment> paymentList;
    private javax.swing.JTextField regNumberTF;
    private javax.swing.JButton searchButton;
    private javax.swing.JComboBox stationComboBox;
    private java.util.List<model.Station> stationList;
    private javax.persistence.Query stationQuery;
    private com.toedter.calendar.JDateChooser toDateField;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    private EntityManager em;
    private List<Payment> payments;
}
